﻿using Application.HFService;
using AppService.CM2Service;
using Domain.Entity;
using Domain.Entity.Fy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace UI7_2.Controllers
{
	public class HFController: Controller
	{
		private readonly IMemoryCache memoryCache;
		private readonly ILogger<HFController> logger;
		private readonly IHFService hFService;

		public HFController(IMemoryCache memoryCache, ILogger<HFController> logger, IHFService hFService)
		{
			this.memoryCache = memoryCache;
			this.logger = logger;
			this.hFService = hFService;
		}
		
		public IActionResult HF()
		{
			return View();
		}
		public IActionResult HF2()
		{
			return View();
		}
		public IActionResult HF3()
		{
			return View();
		}
		//人力资源档案登记复核表
		public IActionResult HR()
		{
			return View();
		}
		public IActionResult DeleHF()
		{
			return View();
		}
		public async Task<bool> DeleteHF(int id)
		{

			return await hFService.DeleteHF(id);
		}
		//查状态为通过复核的数据
		public List<HF> TiaojianHF(string HumanFileStatus)
		{
			string cacheKey = $"FilteredData_{HumanFileStatus}"; // 缓存键名
			var cachedData = memoryCache.Get<List<HF>>(cacheKey); // 从缓存中获取数据
			if (cachedData == null)
			{
				logger.LogInformation("从数据库查询");
				cachedData = hFService.SelectHf(HumanFileStatus);
				// 存储到缓存
				memoryCache.Set(cacheKey, cachedData, new TimeSpan(0, 0, 5));
			}
			else
			{
				logger.LogInformation("从缓存中获取");
			}
			return cachedData;
		}
		public HFFy GetHFFys(int currentPage, int pageSize, string HumanFileStatus)
		{
			string cacheKey = $"FilteredData_{currentPage}_{pageSize}"; // 缓存键名
			var cachedData = memoryCache.Get<HFFy>(cacheKey); // 从缓存中获取数据
			if (cachedData == null)
			{
				logger.LogInformation("从数据库查询");
				cachedData = hFService.GetHFFy(currentPage, pageSize, HumanFileStatus);
				// 存储到缓存
				memoryCache.Set(cacheKey, cachedData, new TimeSpan(0, 0, 5));
			}
			else
			{
				logger.LogInformation("从缓存中获取");
			}
			return cachedData;
		}
		//图片
		public async Task<IActionResult> Upload()
		{
			try
			{
				var file = Request.Form.Files[0]; // Assuming only one file is uploaded
				if (file == null || file.Length == 0)
				{
					return BadRequest("File is empty");
				}
				// Save the uploaded file to a physical path on the server
				var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");
				if (!Directory.Exists(uploadsFolder))
				{
					Directory.CreateDirectory(uploadsFolder);
				}
				var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
				var filePath = Path.Combine(uploadsFolder, fileName);

				using (var stream = new FileStream(filePath, FileMode.Create))
				{
					await file.CopyToAsync(stream);
				}
				// Return the URL of the uploaded file
				var baseUrl = $"{Request.Scheme}://{Request.Host}";
				var imageUrl = $"{baseUrl}/uploads/{fileName}";
				return Ok(new { url = imageUrl });
			}
			catch (Exception ex)
			{
				return StatusCode(500, $"Internal server error: {ex.Message}");
			}
		}
		public Task<bool> Addhf(HFDto hFDto)
		{
			return hFService.HFAdd(hFDto);
		}
		//修改档案状态
		public Task<bool> UpdateHFfuHe(HFDto hF)
		{
			return hFService.Updatehf(hF);
		}
		//多条件查询档案状态为复核通过的数据
		public List<HF> GetHFs(string HumanFileStatus, string? FirstKindName, string? SecondKindName, string? ThirdKindName, string? HumanMajorKindName, string? HunmaMajorName, DateTime? startDate, DateTime? endDate)
		{
			string cacheKey = $"FilteredData_{HumanFileStatus}"; // 缓存键名
			var cachedData = memoryCache.Get<List<HF>>(cacheKey); // 从缓存中获取数据
			if (cachedData == null)
			{
				logger.LogInformation("从数据库查询");
				cachedData = hFService.GetHF(HumanFileStatus, FirstKindName, SecondKindName, ThirdKindName, HumanMajorKindName, HunmaMajorName, startDate, endDate);
				// 存储到缓存
				memoryCache.Set(cacheKey, cachedData, new TimeSpan(0, 0, 5));
			}
			else
			{
				logger.LogInformation("从缓存中获取");
			}
			return cachedData;
			//return hFService.GetHF(HumanFileStatus, FirstKindName, SecondKindName, ThirdKindName, HumanMajorKindName, HunmaMajorName, startDate, endDate);
		}

		//修改档案表
		public Task<bool> UpdateHF(HFDto hF)
		{
			return hFService.Updatehfbiao(hF);
		}
		//修改删除和恢复状态UpdatehfHumanFileStatus
		public Task<bool> xiougaiHFHumanFileStatus(HFDto hF) 
		{ 
			return hFService.UpdatehfHumanFileStatus(hF);
		}


		//文件上传
		[HttpPost]
		public async Task<IActionResult> UploadDocument()
		{
			try
			{
				// Check if the request contains multipart/form-data
				if (!Request.HasFormContentType || !Request.Form.Files.Any())
				{
					return BadRequest("No files uploaded");
				}

				var file = Request.Form.Files[0]; // Assuming only one file is uploaded
				if (file == null || file.Length == 0)
				{
					return BadRequest("File is empty");
				}

				// Validate file type and size
				var allowedExtensions = new[] { ".ppt", ".pptx", ".doc", ".docx", ".txt" };
				var maxFileSize = 20 * 1024 * 1024; // 20 MB
				var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();

				if (!allowedExtensions.Contains(fileExtension))
				{
					return BadRequest("Unsupported file type");
				}

				if (file.Length > maxFileSize)
				{
					return BadRequest("File size exceeds the limit");
				}

				// Save the uploaded file to a physical path on the server
				var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");
				if (!Directory.Exists(uploadsFolder))
				{
					Directory.CreateDirectory(uploadsFolder);
				}

				var fileName = Guid.NewGuid().ToString() + fileExtension;
				var filePath = Path.Combine(uploadsFolder, fileName);

				using (var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
				{
					await file.CopyToAsync(stream);
				}

				// Return the URL of the uploaded file
				var baseUrl = $"{Request.Scheme}://{Request.Host}";
				var fileUrl = $"{baseUrl}/uploads/{fileName}";
				return Ok(new { url = fileUrl });
			}
			catch (IOException ioEx)
			{
				// Handle file system-related exceptions
				return StatusCode(500, $"File system error: {ioEx.Message}");
			}
			catch (UnauthorizedAccessException uaEx)
			{
				// Handle authorization exceptions
				return StatusCode(403, $"Access denied: {uaEx.Message}");
			}
			catch (Exception ex)
			{
				// General exception handling
				return StatusCode(500, $"Internal server error: {ex.Message}");
			}
		}
	}
}
